package com.example.bidding.service;

import com.alibaba.fastjson.JSON;
import com.example.bidding.feign.UserFeign;
import com.example.bidding.mapper.*;
import com.example.common.Ov.*;
import com.example.common.entity.ResponseCode;
import com.example.common.entity.Rsp;
import com.example.common.pojo.*;
import io.lettuce.core.output.DoubleOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BorrowService {

    @Autowired
    private BorrowTypeMapper borrowTypeMapper;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private RepayRecordMapper repayRecordMapper;

    @Autowired
    private LoanMapper loanMapper;

    @Autowired
    private ReprofitRecordMapper reprofitRecordMapper;

    @Autowired
    private TransCodeMapper transCodeMapper;

    //放标
    public Rsp add(UserOv userOv, Borrow borrow) {
        User user1 = new User();
        user1.setId(userOv.getId());
        //判断是否为会员和信誉等级是否达到3级和账号已经激活
        Rsp rsp = userFeign.getUserInfoById(user1);
        User user = JSON.parseObject(JSON.toJSONString(rsp.getResult()),User.class);
        if (user.getMemberType() == 1 && user.getStatus().equals("1") && user.getReputationId()<=3) {
            String borrowTypeName1=borrow.getBorrowTypeName();
            String borrowTypeName2=borrow.getBorrowTypeName2();
            String borrowPurpose = borrow.getBorrowPurpose();
            Integer borrowTypeId=-1;
            List<String> list=borrow.getList();

            if(borrowTypeName1.equals("-1")&&borrowTypeName2.equals("-1")){
                return new Rsp(1, "借款的类型不能为空！");
            }else if(!borrowTypeName1.equals("-1")&& borrowTypeName2.equals("-1")){
                switch (borrowTypeName1){
                    case "0":
                        borrowTypeId=1;
                        break;
                    case "1":
                        borrowTypeId=2;
                        break;
                    case "2":
                        borrowTypeId=3;
                        break;
                    case "3":
                        borrowTypeId=4;
                        break;
                    case "4":
                        borrowTypeId=5;
                        break;
                }
            }else if(!borrowTypeName2.equals("-1")&& borrowTypeName1.equals("-1")){
                switch (borrowTypeName2){
                    case "0":
                        borrowTypeId=1;
                        break;
                    case "1":
                        borrowTypeId=3;
                        break;
                    case "2":
                        borrowTypeId=4;
                        break;
                    case "3":
                        borrowTypeId=5;
                        break;
                }
            }

            //添加进入数据库
            borrow.setBorrowTypeId(borrowTypeId);


            if(borrowPurpose.equals("-1")){
                return new Rsp(1, "借款用途不能为空！");
            }else {
                switch (borrowPurpose) {
                    case "0":
                        borrowPurpose = "个人消费";
                        break;
                    case "1":
                        borrowPurpose = "商业融资";
                        break;
                    case "2":
                        borrowPurpose = "房车贷";
                        break;
                    case "3":
                        borrowPurpose = "其他";
                        break;
                }
            }
            String picture = "";
            System.out.println(list.toString());
            if(!list.toString().equals("[]")){
                for(String p : list){
                    picture=picture+p+",";
                }
                picture=picture.substring(0,picture.lastIndexOf(","));
                borrow.setPicture(picture);
            }

            borrow.setBorrowPurpose(borrowPurpose);
            borrow.setUserId(user.getId());
            borrow.setServiceFeeId(1);
            int i = borrowMapper.insertSelective(borrow);

            if (i != 0) {
                return new Rsp(0, "投标成功！");
            } else {
                return new Rsp(1, "投标失败！");
            }
        }else {
            return new Rsp(1, "还没资格借钱");
        }
    }


    //查看还有多少钱没有还完和总的还款的时间
    public Rsp getBorrowDet(UserOv userOv) {
        //通过id来查找该用户的借钱表
        BigDecimal noMoney = new BigDecimal(0);
        RepayRecordOv repayRecordOv = new RepayRecordOv();

        //创建一个时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

        String day = "2020-01-01";
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(userOv.getId());
        if(borrowList.size()==0){
            repayRecordOv.setUnRepayMoney(noMoney);
            repayRecordOv.setStartTime(day);
            repayRecordOv.setEndTime(day);
            return new Rsp(ResponseCode.SUCCESS,repayRecordOv,"获取成功");
        }


        //通过borrowId来查找还款的记录
        List<RepayRecord> recordList = getRecordListByIds(borrowList);


        //计算其未还款的金额
        for(RepayRecord r : recordList){
            if(r.getStatus()==0){
                noMoney=noMoney.add(r.getRepayMoney());
            }
        }
        repayRecordOv.setUnRepayMoney(noMoney);

        Borrow borrow = borrowList.get(0);
        Date borrowFullTime = borrow.getBorrowFullTime();
        Date repaymentDate = borrow.getRepaymentDate();
        String format = sdf.format(borrowFullTime);
        String format2 = sdf.format(repaymentDate);
        String fullTime = format.substring(0, 10);
        String repayment = format2.substring(0, 10);
        repayRecordOv.setStartTime(fullTime);
        repayRecordOv.setEndTime(repayment);

        return new Rsp(ResponseCode.SUCCESS,repayRecordOv,"获取成功");
    }

    public Rsp getUserInfo(String token) {
        UserInfoOv userInfo = getBorrByUserId(token);
        BigDecimal noMoney = new BigDecimal(0);
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(userInfo.getId());
        if(borrowList.size()==0){
            return new Rsp(ResponseCode.SUCCESS,userInfo,"获取成功");
        }

        boolean flag=true;
        for(Borrow b : borrowList){
            if(b.getBorrowTypeId()>3){
                flag=false;
            }
        }

        if(flag){
            return new Rsp(ResponseCode.SUCCESS,userInfo,"获取成功");
        }


        //通过borrowId来查找还款的记录
        List<RepayRecord> recordList = getRecordListByIds(borrowList);

        //计算其未还款的金额
        for(RepayRecord r : recordList){
            if(r.getStatus()==0){
                noMoney=noMoney.add(r.getRepayMoney());
            }
        }
        userInfo.setQuota(userInfo.getQuota().subtract(noMoney));
        return new Rsp(ResponseCode.SUCCESS,userInfo,"获取成功");
    }

    //获取用户的还款详情
    public Rsp getRepayRecord(String token) {
        UserInfoOv userInfo = getBorrByUserId(token);
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(userInfo.getId());
        if(borrowList.size()==0){
            return new Rsp(ResponseCode.ERROR,"该用户没有成功的借款");
        }

        List<RepayRecord> recordList = getRecordListByIds(borrowList);
        return new Rsp(ResponseCode.SUCCESS,recordList,"获取成功");
    }


    //通过userID来获取userinfo(普通方法)
    public UserInfoOv getBorrByUserId(String token){
        Rsp rsp = userFeign.getUserInfo(token);
        UserInfoOv userInfo = JSON.parseObject(JSON.toJSONString(rsp.getResult()),UserInfoOv.class);
        return userInfo;
    }


    //通过borrowId来查找还款的记录(普通方法)
    public List<RepayRecord> getRecordListByIds(List<Borrow> borrowList){
        //获取借钱的id们
        List<Integer> list = new ArrayList<>();
        for(Borrow b : borrowList){
            list.add(b.getId());
        }
        //通过borrowId来查找还款的记录
        List<RepayRecord> recordList = repayRecordMapper.selectByBorrowId(list);
        return recordList;
    }


    //获取还款详情
    public Rsp getRepayDetilByRepayRecordId(RepayRecord repayRecord) {
        RepayOv repayOv = repayRecordMapper.getRepayDetilByRepayRecordId(repayRecord.getId());
        double borrowMoney = repayOv.getBorrowMoney().doubleValue();
        double borrowRate=repayOv.getBorrowRate();
        double borrowRateMoney = borrowMoney*(borrowRate/100);
        //计算总的欠的金额
        Double totalMoney = 0.0;
        totalMoney=borrowMoney+borrowRateMoney+repayOv.getMoney().doubleValue();
        repayOv.setTotalMoney(totalMoney);

        if(StringUtils.isEmpty(repayOv)){
            return new Rsp(ResponseCode.ERROR,"获取失败");
        }else{
            return new Rsp(ResponseCode.SUCCESS,repayOv,"获取成功");
        }
    }

    //获取借钱的记录
    public Rsp getBorrowListByUserId(Integer userId) {
        List<Borrow> borrowList=borrowMapper.getBorrowListByUserId(userId);
        if(borrowList.size()==0){
            return new Rsp(ResponseCode.ERROR,"该用户没有借款记录");
        }else{
            return new Rsp(ResponseCode.SUCCESS,borrowList,"获取成功");
        }
    }

    //获取用户的还款详情通过userId和borrowId两个参数获取
    public Rsp getRepayRecordByBorrowId(Integer borrowId) {
        List<Integer> list =new ArrayList<>();
        list.add(borrowId);
        List<RepayRecord> recordList = repayRecordMapper.selectByBorrowId(list);
        return new Rsp(ResponseCode.SUCCESS,recordList,"获取成功");
    }

    //获取还款记录
    public Rsp getRepayRecordByUserId(Integer userId) {
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(userId);
        if(borrowList.size()==0){
            return new Rsp(ResponseCode.ERROR,"该用户没有需要还的还款");
        }
        List<RepayRecord> list =new ArrayList<>();
        List<RepayRecord> recordListByIds = getRecordListByIds(borrowList);
        for(RepayRecord re : recordListByIds){
            if(re.getStatus()==1){
                list.add(re);
            }
        }
        return new Rsp(ResponseCode.SUCCESS,list,"获取成功");
    }

    //获取未还款的记录
    public Rsp getRepayRecordByUserId2(Integer id) {
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(id);
        if(borrowList.size()==0){
            return new Rsp(ResponseCode.ERROR,"该用户没有需要还的还款");
        }
        List<RepayRecord> loanlist =new ArrayList<>();
        BigDecimal noMoney = new BigDecimal(0);
        Integer count = 0;
        List<RepayRecord> recordListByIds = getRecordListByIds(borrowList);
        for(RepayRecord re : recordListByIds){
            if(re.getStatus()==0){
                loanlist.add(re);
                noMoney=noMoney.add(re.getRepayMoney());
                count++;
            }
        }
        BigDecimal checkMoney = getCheckMoney(id);
        for(RepayRecord r : recordListByIds){
            r.setTotalMoney(noMoney);
            r.setCount(count);
            r.setCheckMoney(checkMoney);
        }


        return new Rsp(ResponseCode.SUCCESS,loanlist,"获取成功");
    }

    //获取被选中的还款的金额和修改是否被选中
    public Rsp getCheckMoney(RepayRecord repayRecord,Integer userId) {
        //通过主键来获取相应的还款单号
        RepayRecord repayRecord1 = repayRecordMapper.selectByPrimaryKey(repayRecord.getId());
        if(repayRecord1.getIsCheck()==0){
            repayRecord1.setIsCheck(1);
        }else{
            repayRecord1.setIsCheck(0);
        }
        int i = repayRecordMapper.updateByRepayRecord(repayRecord1);
        BigDecimal checkMoney = getCheckMoney(userId);
        if(i!=0){
            return new Rsp(ResponseCode.SUCCESS,checkMoney,"获取成功");
        }else{
            return new Rsp(ResponseCode.ERROR,"获取失败");
        }
    }

    //获取选中商品的总额
    public BigDecimal getCheckMoney(Integer userId){
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(userId);
        BigDecimal checkMoney = new BigDecimal(0);
        List<RepayRecord> recordList= getRecordListByIds(borrowList);
        for(RepayRecord re : recordList){
            if(re.getIsCheck()==1){
                checkMoney=checkMoney.add(re.getRepayMoney());
            }
        }
        return checkMoney;
    }

    //支付
    public Rsp pay(String token, User user) {
        UserInfoOv userInfoOv = getBorrByUserId(token);
        if(userInfoOv.getPayPassword().equals(user.getPayPassword())){
            payMethod(userInfoOv,user);
            //获取还款的金额
            BigDecimal checkMoney = getCheckMoney(userInfoOv.getId());
            //修改user的余额
            userFeign.subBalance(user,checkMoney);
            return new Rsp(ResponseCode.SUCCESS,"支付成功！！");
        }else{
            return new Rsp(ResponseCode.ERROR,"支付密码错误！！");
        }
    }

    //支付的许多方法的方法
    public void payMethod(UserInfoOv userInfoOv,User user){
        user.setId(userInfoOv.getId());
        user.setBalance(userInfoOv.getBalance());

        //获取该用户端的所有还款订单记录
        List<Borrow> borrowList = borrowMapper.selectBorrowByUserId(userInfoOv.getId());
        List<RepayRecord> recordList= getRecordListByIds(borrowList);

        //获取被选中的订单的编号
        Set<Integer> set = new HashSet<>();//获取borrowId的集合
        List<Integer> list = new ArrayList<>();
        for(RepayRecord r : recordList){
            if(r.getIsCheck()==1){
                list.add(r.getId());
                set.add(r.getBorrowId());
            }
        }

        //通过IDS去找loans
        List<LoanOv> loanOvList = loanMapper.getLoansByRepayIds(list);

        //获取其id的集合
        List<Integer> list2 = new ArrayList<>();
        for(LoanOv l : loanOvList){
            list2.add(l.getId());
        }
        //修改reprofit_record表中的状态
        reprofitRecordMapper.updateStatusByIds(list2);

        //加钱
        for(LoanOv loan : loanOvList){
            User user1 = new User();
            user1.setId(loan.getUserId());
            Rsp rsp = userFeign.getUserInfoById(user1);
            User userInfo = JSON.parseObject(JSON.toJSONString(rsp.getResult()),User.class);
            //System.out.println(userInfo);
            user1.setBalance(userInfo.getBalance());
            BigDecimal addMoney=loan.getReprofitInterest().add(loan.getReprofitMoney());

            double addMoney2=0-addMoney.doubleValue();
            BigDecimal bigDecimal = new BigDecimal(addMoney2);
            userFeign.subBalance(user1,bigDecimal);

            //存消息
            TransCode transCode = new TransCode();
            transCode.setUserId(user1.getId());
            transCode.setContent("您收到一笔"+addMoney+"的还款");
            transCode.setType("还款");
            transCodeMapper.insertSelective(transCode);
        }

        //修改他们的状态为为1，isCheck为2
        repayRecordMapper.updateRepayRecordByIds(list);

        List<Integer> list3 = new ArrayList<>(set);
        //是否还清
        for(Integer borrowId : list3){
            //通过borrowId来查找
            List<RepayRecord> repayRecords = repayRecordMapper.selectByBorrId(borrowId);
            //System.out.println(repayRecords);
            Boolean flag = true;
            for(RepayRecord r :repayRecords){
                //System.out.println(r.getStatus()==0);
                if(r.getStatus()==0){
                    flag=false;
                }
            }
            if(flag){
                Borrow borrow = new Borrow();
                borrow.setId(borrowId);
                borrow.setStatus(3);
                borrowMapper.updateByPrimaryKeySelective(borrow);
            }
        }
    }

}
